import { BaseDatabase } from './base'

export interface Notespace {
  id: string
  name: string
  path: string
  created: number
  lastModified: number
  lastAccessed: number
  settings?: {
    encryption?: {
      enabled: boolean
      algorithm: string
      key?: string
    }
    autoBackup?: {
      enabled: boolean
      interval: number
      maxBackups: number
    }
  }
}

export class NotespaceDatabase extends BaseDatabase {
  constructor() {
    super('notespace')
  }

  createNotespace(notespace: Omit<Notespace, 'id' | 'created' | 'lastModified' | 'lastAccessed'>): string {
    const now = Date.now()
    const id = this.generateId()
    
    const newNotespace: Notespace = {
      ...notespace,
      id,
      created: now,
      lastModified: now,
      lastAccessed: now
    }

    this.db.insert(this.getPath([]), newNotespace)
    return id
  }

  getNotespace(id: string): Notespace | null {
    const result = this.db.query(this.getPath([]), { id })
    return result[0] || null
  }

  listNotespaces(): Notespace[] {
    return this.db.query(this.getPath([]))
      .sort((a, b) => b.lastAccessed - a.lastAccessed)
  }

  updateNotespace(id: string, updates: Partial<Omit<Notespace, 'id' | 'created'>>): void {
    const notespace = this.getNotespace(id)
    if (!notespace) return

    const updatedNotespace = {
      ...notespace,
      ...updates,
      lastModified: Date.now()
    }

    this.db.update(this.getPath([]), updatedNotespace, { id })
  }

  deleteNotespace(id: string): void {
    const notespace = this.getNotespace(id)
    if (!notespace) return

    this.db.delete(this.getPath([]), { id })
  }

  updateLastAccessed(id: string): void {
    const notespace = this.getNotespace(id)
    if (!notespace) return

    this.updateNotespace(id, {
      lastAccessed: Date.now()
    })
  }

  searchNotespaces(query: string): Notespace[] {
    return this.db.query(this.getPath([]))
      .filter(notespace => 
        notespace.name.toLowerCase().includes(query.toLowerCase()) ||
        notespace.path.toLowerCase().includes(query.toLowerCase())
      )
      .sort((a, b) => b.lastAccessed - a.lastAccessed)
  }

  private generateId(): string {
    return Math.random().toString(36).substring(2) + Date.now().toString(36)
  }
}